app.factory('RecordService', function(ConfigMap,UploadService,$timeout) {

	var record = {
		hasRecorded: false,
		isRecording: false,
		countdown:ConfigMap.record.countdown,
		radioSrc: null,
		finalRadioSrc:null,
		mediaRec:null,
		scope:null
	};

    var createNewMedia = function(scope,radioSrc){
    	record.scope = scope;
		record.mediaRec = new Media(radioSrc?radioSrc:record.radioSrc);
	},
	startRecord = function(){
		record.isRecording = true;
		record.mediaRec.startRecord();
		record.radioSrc = ConfigMap.record.defaultRadioUrl;
	    countdown(function(){
        	record.hasRecorded =true;
        	record.isRecording = false;
        	record.mediaRec.stopRecord();
   			record.mediaRec.release();
   			UploadService.uploadWav(record.radioSrc,function(data){
				record.finalRadioSrc = data.msg;
				record.scope.$digest();
			},function(err){
				record.hasRecorded = false;
				record.isRecording = false;
				writeObj(err);
			});
	    });
	},
	stopRecord = function(){
		record.hasRecorded = true;
		record.isRecording = false;
    	record.mediaRec.pause();
		record.mediaRec.release();
	},

	playRecord = function(){
		if(record.mediaRec){
			record.mediaRec.play();
	    }
	},
	reRecord = function(){
		record.isRecording = false;
		record.hasRecorded = false;
	};

	var countdown = function (callback) {
        if (record.countdown === 0) {
            record.countdown = ConfigMap.record.countdown;
            if(callback){
            	callback();
            }
            return;
        } else {
            record.countdown--;
        }
        $timeout(function () {
            countdown(callback);
            record.scope.$digest();
        }, 1000);
    };

	return {
		createNewMedia:createNewMedia,
		startRecord: startRecord,
		playRecord: playRecord,
		stopRecord:stopRecord,
		reRecord:reRecord,
		record:record,
		countdown:countdown
	};
});